<script setup lang="ts">
  import { ref, onMounted, reactive } from 'vue';
  import { useBooleanStore } from '@/store';
  import { Notification } from '@arco-design/web-vue';
  import {
    mdDtTopSearchData,
    topSearchAoData,
    topSearchMatchData,
    deliveryDataQuery,
    palletInCarFunc,
  } from '@/api/material-distribution';
  import DailyDeliveryData from './dailyDeliveryData.vue';

  const booleanStore = useBooleanStore();
  const hStyle = ref({
    'background-color': booleanStore.color,
    'border-radius': booleanStore.borderRadius,
  });
  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'PAGEHELPER_ROW_ID',
      key: 'PAGEHELPER_ROW_ID',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '托盘编码',
      dataIndex: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '小车编码',
      dataIndex: 'carCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '是否装车',
      dataIndex: 'status',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '分拣状态',
      dataIndex: 'sortStatus',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
  ];
  const aoColumns: any[] = [
    {
      title: 'AO号',
      dataIndex: 'aoNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '日计划时间',
      dataIndex: 'dailyTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
  ];
  const matchColumns: any[] = [
    {
      title: '配送状态',
      dataIndex: 'status',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: 'AO号',
      dataIndex: 'aoNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '图号',
      dataIndex: 'itemCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '质量编号',
      dataIndex: 'qualityCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '是否带证',
      dataIndex: 'isPaper',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '合格证号',
      dataIndex: 'mesCheckQualiticationId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '装配图号',
      dataIndex: 'repartAss',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '交接数量',
      dataIndex: 'deliveryQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '交接单主键',
      dataIndex: 'wmsDeliveryPlanId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
  ];
  const localTableData = ref<any>();
  const aoTableData = ref<any>();
  const matchTableData = ref<any>();
  const total = ref<number>(1);
  const pageNum = ref<number>(1);
  const pageSize = ref<number>(10);
  const scanData = reactive([
    {
      value: '',
      label: '小车编码',
    },
    {
      value: '',
      label: '工作包器具',
    },
  ]);
  const formValues = reactive({
    planeNo: '',
    station: '',
    carCode: '',
    aoCode: '',
    status: '',
  });
  const deliveryForm = reactive({
    aoCode: '',
    itemCode: '',
  });
  const packageForm = ref<string[]>([]);
  const inputCode = ref<any>();
  const inputData = ref<string>();
  const planeNoInput = ref<boolean>(false);
  async function handleSearch() {
    if (!formValues.planeNo) {
      planeNoInput.value = true;
      Notification.error({
        title: '错误',
        content: '架次不能为空',
        closable: true,
      });
    } else {
      const response = await mdDtTopSearchData({
        queryParam: formValues,
        page: { currentPage: pageNum.value, pageSize: pageSize.value },
      });
      if (response.list) {
        total.value = response.total;
        pageSize.value = response.pageSize;
        localTableData.value = response.list;
      }
    }
  }
  async function tableClick(record: any) {
    const aoResponse = await topSearchAoData(record);
    if (aoResponse) {
      aoTableData.value = aoResponse;
    }
    const matchResponse = await topSearchMatchData(record);
    if (matchResponse) {
      matchTableData.value = matchResponse;
    }
  }
  async function matchSearch() {
    const matchResponse = await topSearchMatchData(deliveryForm);
    if (matchResponse) {
      matchTableData.value = matchResponse;
    }
  }
  onMounted(() => {
    inputCode.value.focus();
  });
  function inputDataCleanAndFocus() {
    inputData.value = '';
    setTimeout(() => {
      inputCode.value.focus();
    }, 100);
  }
  async function deliveryBtn() {
    if (!scanData[0].value) {
      Notification.error({
        title: '错误',
        content: '请先扫描小车编码',
        closable: true,
      });
      return;
    }
    if (packageForm.value.length === 0) {
      Notification.error({
        title: '错误',
        content: '请先扫描工作包器具编码',
        closable: true,
      });
      return;
    }
    const response = await deliveryDataQuery({
      carCode: scanData[0].value,
      toolCodes: packageForm.value,
    });
    if (response.retCode === '200') {
      Notification.success({
        title: '成功',
        content: response.message,
        closable: true,
      });
      packageForm.value = [];
      scanData[0].value = '';
      scanData[1].value = '';
    } else {
      Notification.error({
        title: '错误',
        content: response.message ? response.message : '配送失败',
        closable: true,
      });
    }
    inputDataCleanAndFocus();
  }
  async function palletInCar() {
    if (!scanData[0].value) {
      Notification.error({
        title: '错误',
        content: '请先扫描小车编码',
        closable: true,
      });
      return;
    }
    const response = await palletInCarFunc({
      carCode: scanData[0].value,
      toolCodes: packageForm.value,
    });
    if (response.retCode === '200') {
      Notification.success({
        title: '成功',
        content: response.message,
        closable: true,
      });
      packageForm.value = [];
      // scanData[0].value = '';
      scanData[1].value = '';
    } else {
      Notification.error({
        title: '错误',
        content: response.message ? response.message : '配送失败',
        closable: true,
      });
    }
    inputDataCleanAndFocus();
  }
  function inputCodeValueChanged() {
    // 空识别
    if (!inputData.value) {
      return;
    }
    // 扫小车码
    if (inputData.value.indexOf('L-D-') > -1) {
      scanData[0].value = inputData.value;
      inputDataCleanAndFocus();
      return;
    }
    // 扫工作包器具
    if (inputData.value.length === 12) {
      // 第一次扫工作包，直接拼接
      if (packageForm.value.length === 0) {
        scanData[1].value += inputData.value;
        scanData[1].value += ',';
        packageForm.value.push(inputData.value);
        inputDataCleanAndFocus();
        return;
      }
      // 已经有数据了，判断是否重复扫
      if (packageForm.value.some((data: string) => data === inputData.value)) {
        Notification.error({
          title: '错误',
          content: `${inputData.value}已扫码,请勿重复扫码`,
          closable: true,
        });
      } else {
        scanData[1].value += inputData.value;
        scanData[1].value += ',';
        packageForm.value.push(inputData.value);
      }
      inputDataCleanAndFocus();
    }
    // 9005直接调配送接口
    else if (inputData.value === '9005') {
      deliveryBtn();
    } else {
      Notification.error({
        title: '错误',
        content: '无法识别该二维码',
        closable: true,
      });
      inputDataCleanAndFocus();
    }
  }
  function reset() {
    Object.keys(formValues).forEach((key) => {
      (formValues as Record<string, any>)[key] = '';
    });
    setTimeout(() => {
      handleSearch();
    }, 150);
  }
  // 监听已选择数据的序号，并更新到已选择表格数据行字段
  function change(e: any) {
    pageNum.value = e;
  }
  function changeSize(e: any) {
    pageSize.value = e;
  }
</script>

<template>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title> <div class="font">每日配送任务数据</div> </template>
    <DailyDeliveryData />
  </a-card>
  <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="12">
      <a-card :header-style="hStyle" :bordered="false">
        <template #title> <div class="font">扫码操作</div> </template>
        <div>
          <span style="font-size: large; font-weight: 600">条码:</span>
          <a-input
            ref="inputCode"
            v-model:model-value="inputData"
            :style="{ width: '350px' }"
            placeholder="请扫描或输入缓存箱/托盘码/条码"
            @press-enter="inputCodeValueChanged"
          />
          <a-space style="margin-left: 8px">
            <a-button type="primary" size="large" @click="palletInCar"
              >托盘装车</a-button
            >
            <a-button type="primary" size="large" @click="deliveryBtn">
              配送
            </a-button>
          </a-space>
        </div>
      </a-card>
    </a-col>
    <a-col :span="12">
      <a-card :header-style="hStyle" :bordered="false">
        <template #title> <div class="font">扫码数据</div> </template>
        <a-descriptions
          size="medium"
          :data="scanData"
          bordered
          :column="2"
          layout="vertical"
        />
      </a-card>
    </a-col>
  </a-row>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title> <div class="font">待配送工作包任务列表</div> </template>
    <div class="content">
      <a-input
        v-model="formValues.planeNo"
        size="large"
        placeholder="架次"
        :error="planeNoInput"
      />
      <a-input v-model="formValues.aoCode" size="large" placeholder="AO号" />
      <a-input v-model="formValues.station" size="large" placeholder="站位" />
      <a-input
        v-model="formValues.carCode"
        size="large"
        placeholder="小车编码"
      />
      <a-select
        v-model="formValues.status"
        placeholder="是否装车"
        size="large"
        default-value=""
      >
        <a-option label="已装车" value="I" />
        <a-option label="未装车" value="W" />
        <a-option label="已配送" value="S" />
      </a-select>
    </div>
    <div style="margin-top: 16px">
      <a-space>
        <a-button type="primary" size="large" @click="handleSearch">
          查询
        </a-button>
        <a-button size="large" @click="reset">重置</a-button>
      </a-space>
    </div>
  </a-card>
  <a-table
    :stripe="true"
    class="top-table"
    :pagination="false"
    :columns="columns"
    :data="localTableData"
    row-key="PAGEHELPER_ROW_ID"
    @row-click="tableClick"
  >
  </a-table>
  <div class="page-position" style="margin-bottom: 8px">
    <a-pagination
      :total="total"
      :current="pageNum"
      :page-size="pageSize"
      show-total
      show-jumper
      show-page-size
      @change="change"
      @update:page-size="changeSize"
    />
  </div>
  <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="12">
      <a-table
        :stripe="true"
        class="top-table"
        :columns="aoColumns"
        :data="aoTableData"
      />
    </a-col>
    <a-col :span="12">
      <a-row :gutter="{ md: 8, lg: 24, xl: 32 }" style="margin-bottom: 8px">
        <a-col :span="8">
          <a-input
            v-model="deliveryForm.aoCode"
            placeholder="AO号"
            size="large"
            @press-enter="handleSearch"
          />
        </a-col>
        <a-col :span="8">
          <a-input
            v-model="deliveryForm.itemCode"
            placeholder="图号"
            size="large"
            @press-enter="handleSearch"
          />
        </a-col>
        <a-col :span="8">
          <a-button type="primary" size="large" @click="matchSearch"
            >查询
          </a-button>
        </a-col>
      </a-row>
      <a-table
        :stripe="true"
        class="top-table"
        :columns="matchColumns"
        :data="matchTableData"
      />
    </a-col>
  </a-row>
</template>

<style scoped>
  .arco-col-6 {
    margin-bottom: 16px;
  }
  .top-table {
    white-space: nowrap;
  }
  .page-position {
    margin-top: 20px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .content {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    grid-column-gap: 10px;
  }
  .demo-trigger {
    padding: 10px;
    width: 200px;
    background-color: var(--color-bg-popup);
    border-radius: 4px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.15);
  }
  .font {
    font-size: 20px;
    color: black;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }
</style>
